// pages/confirmorder/confirmorder.js
var app = getApp();
var utils = require('../../utils/util.js');
Page({
    data: {
		textValue:""
	},

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        var that = this;
        that.setData({
         store_id: options.store_id,
        });
		wx.getSystemInfo({
			success(res) {
				that.setData({
					resinfo: res.SDKVersion
				})
			}
		})
        that.getStoreInfo();
        that.getCartList();
    },
    onShow:function(){

        var that = this;
        that.getAddressInfo();
    },

	//获取站点配置信息 
	systemInfo: function () {
		var that = this;
		utils.http("/api/v1/common/system", {}, function (res) {
			if (res.state == 1) {
				if (that.data.cart_total.amount < that.data.store_info.reduce_need){
					var total = parseFloat(res.datas.dis_money) + parseFloat(that.data.cart_total.amount);
				}else{
					var total = parseFloat(res.datas.dis_money) + (parseFloat(that.data.cart_total.amount) - parseFloat(that.data.store_info.reduce_price));
				}
				

				that.setData({
					system: res.datas,
					total: total.toFixed(2)
				})

			} else {
				utils.message(res.datas)
			}
		})
	},
    // 获取地址信息
    getAddressInfo: function() {
        var that = this;
        console.log(app.globalData.addressChid);
        if (app.globalData.addressChid != undefined) {
            utils.http("/api/v1/address/address_info", {
                address_id: app.globalData.addressChid,
                school_id: wx.getStorageSync('schoolInfo').schoolid,
            }, function(res) {
                app.globalData.addressChid = undefined;
                that.setData({
                    defaultAddress: res.datas,
                    addressId: res.datas.id
                })
            })
        } else {
            utils.http("/api/v1/address/address_info", {
                school_id: wx.getStorageSync('schoolInfo').schoolid
            }, function(res) {
                console.log(res);
                if (res.datas != null) {
                    that.setData({
                        defaultAddress: res.datas,
                        addressId: res.datas.id
                    })
                }
            })
        }
    },
    // 获取 店铺信息
    getStoreInfo:function() {
        var that = this;
       	utils.showLoading();
        utils.http("/api/v1/store/store_detail", {
            store_id: that.data.store_id,
            latitude: wx.getStorageSync("localhost").latitude,
            longitude: wx.getStorageSync("localhost").longitude
        }, function(res) {
            if (res.state == 1) {
	            that.setData({
	                store_info: res.datas,
	            })
	            utils.hideLoading();
            } else {
            	utils.hideLoading();
                utils.message(res.datas)
            }
        })
    },
    // 获取购物车信息
    getCartList:function(){
        var that = this;
       	utils.showLoading();
        utils.http("/api/v1/cart/cart_list", {
            store_id: that.data.store_id,
        }, function (res) {
            if (res.state == 1) {
                that.setData({
                    cart_list: res.datas.cart_list,
                    cart_total: res.datas.cart_total,
                })

				that.systemInfo();
            	utils.hideLoading();
            } else {
            	utils.hideLoading();
                utils.message(res.datas)
            }
        })
    },
    makePhone:function(e){
    	wx.makePhoneCall({
			phoneNumber: e.currentTarget.dataset.phone,
		})
    },
    //打开支付弹窗
    toPay: function(e) {
        var that = this;
		console.log(that.data.resinfo,"klsdjfklsdjfkl")
		var a = that.data.resinfo.split(".").join("");
		var str = "2.8.2"
		var b = str.split(".").join("");
		console.log(a, b)
		if (a < b) {
			console.log("基础库2.8.2以上才支持哈")
			utils.showSuccess("基础库2.8.2以上才支持哈", "none", false, 2000)
			//成功
			utils.confirm("下单后订单不可退哦，确认下单？", function (res) {
				console.log(res);
				if (!res.cancel) {
					if (!that.data.addressId) {
						utils.showSuccess('请填写地址', 'none');
						return false;
					}
					utils.showLoading();
					var param = {
						store_id: that.data.store_id,
						address_id: that.data.addressId,
						order_remark: that.data.textValue
					};
					utils.http("/api/v1/order/add_order_v2", param, function (res) {
						utils.hideLoading();
						if (res.state == 1) {
							wx.requestPayment({
								timeStamp: res.datas.timeStamp,
								nonceStr: res.datas.nonceStr,
								package: res.datas.package,
								signType: res.datas.signType,
								paySign: res.datas.paySign,
								success() {

									that.paySuccessCallback(res);
								},
								fail(res) {
									that.setData({
										buttonClicked: false
									})
									wx.switchTab({
										url: '../order/order',
									})
								}
							})
						} else if (res.state == 10001) {

							that.paySuccessCallback(res)
						} else {
							utils.message(res.datas);
						}
					})
				} else {

				}

			})
		} else {
			wx.requestSubscribeMessage({
				tmplIds: ["WlOZv5TjFsjUmFW1Rwo6ZxrD6H6y3_ygZ2Bh1aEMFc8"],
				success: function (res1) {
					console.log(res1)
					if (res1.WlOZv5TjFsjUmFW1Rwo6ZxrD6H6y3_ygZ2Bh1aEMFc8 == "accept") {
						//成功
						utils.confirm("下单后订单不可退哦，确认下单？", function (res) {
							console.log(res);
							if (!res.cancel) {
								if (!that.data.addressId) {
									utils.showSuccess('请填写地址', 'none');
									return false;
								}
								utils.showLoading();
								var param = {
									store_id: that.data.store_id,
									address_id: that.data.addressId,
									order_remark: that.data.textValue
								};
								utils.http("/api/v1/order/add_order_v2", param, function (res) {
									utils.hideLoading();
									if (res.state == 1) {
										wx.requestPayment({
											timeStamp: res.datas.timeStamp,
											nonceStr: res.datas.nonceStr,
											package: res.datas.package,
											signType: res.datas.signType,
											paySign: res.datas.paySign,
											success() {

												that.paySuccessCallback(res);
											},
											fail(res) {
												that.setData({
													buttonClicked: false
												})
												wx.switchTab({
													url: '../order/order',
												})
											}
										})
									} else if (res.state == 10001) {

										that.paySuccessCallback(res)
									} else {
										utils.message(res.datas);
									}
								})
							} else {

							}

						})

					} else {
						console.log("cuowu")
					}

				},
				fail(err) {
					//失败
					console.error(err);
				}
			})
		}



       
    },
	paySuccessCallback: function (res){
		console.log(res.datas.order_id)
    	wx.navigateTo({
			url: '../orderDetil/orderDetil?order_id=' + res.datas.order_id
    	});
    },
    //跳入我的地址页面
    onMyAddressTap: function(e) {
        app.globalData.typeaddress = 0
        wx.navigateTo({
            url: '../address/address',
        })
    },


	//输入备注
	onTextAreabeiTap:function(e){
	//	console.log(e.detail.value)
		this.setData({
			textValue: e.detail.value
		})
	}
})